package com.net.xpay.web.controller.merchant;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.xpay.web.vo.AccountLogVo;
import com.net.common.dao.OrderCondition;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.domain.AccountLog;
import com.net.xpay.core.domain.PayTransSummary;
import com.net.xpay.core.domain.safePay.SafePayBatch;
import com.net.xpay.core.enums.AccountBillType;
import com.net.xpay.core.enums.AccountFundType;
import com.net.xpay.core.manager.AccountLogManager;
import com.net.xpay.core.manager.PayTransSummaryManager;
import com.net.xpay.core.manager.safePay.SafePayBatchManager;
import com.net.xpay.core.model.AccountLogSearchModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**

 */
@RestController
@Slf4j
@RequestMapping("/merchant/account-log")
@Api(tags = "商户/资金明细", description = "商户 资金明细 net")
public class AccountLogController {

    @Autowired
    private AccountLogManager accountLogManager;

    @Autowired
    private SafePayBatchManager safePayBatchManager;

    @Autowired
    private PayTransSummaryManager payTransSummaryManager;


    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    public ResultPagedList<AccountLogVo> search(@ApiIgnore @RequestUser User merchant, @RequestBody AccountLogSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());
        searchModel.setAccountFundType(AccountFundType.MONEY);
        searchModel.setColumn("create_time");
        searchModel.setOrderby(OrderCondition.ORDER_BY_DESC);
        List<AccountLog> records = accountLogManager.search(searchModel);
        List<AccountLogVo> vos = BeanCopierUtil.batchCopy(AccountLog.class, AccountLogVo.class, records);
        for (AccountLogVo vo : vos) {
            //设置相关业务id，查看详情
            if (AccountBillType.SAFE_PAY_TRANS_SERVICE_PRICE.equals(vo.getType()) || AccountBillType.SAFE_PAY_TRANS_SERVICE_PRICE_REFUND.equals(vo.getType())) {
                //安全发服务费和退款
                SafePayBatch batch = safePayBatchManager.getById(vo.getRelatedId());
                if (batch != null) {
                    vo.setRelatedDetailNo(batch.getImportBatchNo());
                    vo.setMemo(batch.getImportBatchNo());
                }

            }
            //批量有密的
            if (AccountBillType.PAY_TRANS_SERVICE_PRICE.equals(vo.getType()) || AccountBillType.PAY_TRANS_SERVICE_PRICE_REFUND.equals(vo.getType())) {
                PayTransSummary summary = payTransSummaryManager.getById(vo.getRelatedId());
                if (summary != null) {
                    vo.setRelatedDetailNo(summary.getImportBatchNo());
                    vo.setMemo(summary.getImportBatchNo());
                }
            }
        }

        long count = accountLogManager.searchCount(searchModel);

        return new ResultPagedList<>(vos, count, searchModel);
    }

    /**
     * 资金明细导出
     */
    @ApiOperation("资金明细导出")
    @GetMapping("/export")
    public ResultData<Boolean> exportAccountLog(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);
        AccountLogSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, AccountLogSearchModel.class);
        searchModel.setUserId(merchant.getId());
        searchModel.setAccountFundType(AccountFundType.MONEY);
        List<AccountLog> accountLogList = accountLogManager.list(searchModel);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();

        model.put("records", accountLogList);

        String fileName = "资金明细.xlsx";
        String template = "/excel/tpl/资金明细.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }
}
